package com.keba.lamp.complaint.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.keba.basic.base.service.impl.SuperServiceImpl;
import com.keba.basic.database.mybatis.conditions.Wraps;
import com.keba.basic.database.mybatis.conditions.query.LbQueryWrap;
import com.keba.lamp.common.constant.BizConstant;
import com.keba.lamp.complaint.entity.Agent;
import com.keba.lamp.complaint.entity.ComFileRel;
import com.keba.lamp.complaint.enumeration.AgentTypeEnum;
import com.keba.lamp.complaint.manager.AgentManager;
import com.keba.lamp.complaint.manager.ComFileRelManager;
import com.keba.lamp.complaint.service.AgentService;
import com.keba.lamp.complaint.vo.result.AgentResultVO;
import com.keba.lamp.complaint.vo.result.CaseFileResultVO;
import com.keba.lamp.complaint.vo.save.AgentSaveVO;
import com.keba.lamp.complaint.vo.update.AgentSummarizeUpdateVO;
import com.keba.lamp.complaint.vo.update.AgentUpdateVO;
import com.keba.lamp.file.entity.File;
import com.keba.lamp.file.service.AppendixService;
import com.keba.lamp.file.service.FileService;
import com.keba.lamp.model.vo.result.AppendixResultVO;
import com.keba.lamp.model.vo.save.AppendixSaveVO;
import com.keba.lamp.system.manager.system.DefParameterManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 代理人信息
 * </p>
 *
 * @author chaowu.wang
 * @date 2025-09-13 18:19:51
 * @create [2025-09-13 18:19:51] [chaowu.wang] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AgentServiceImpl extends SuperServiceImpl<AgentManager, Long, Agent> implements AgentService {
    private final AppendixService appendixService;
    private final FileService fileService;
    private final ComFileRelManager comFileRelManager;
    private final DefParameterManager defParameterManager;

    @Override
    public void save(List<AgentSaveVO> plaintffAgentSaveVOList, List<AgentSaveVO> defendantAgentSaveVOList, Long caseId) {
        //原告代理人
        if (CollectionUtil.isNotEmpty(plaintffAgentSaveVOList)) {
            saveAgent(plaintffAgentSaveVOList, AgentTypeEnum.PLAINTFF, caseId);
        }
        //被告代理人
        if (CollectionUtil.isNotEmpty(defendantAgentSaveVOList)) {
            saveAgent(defendantAgentSaveVOList, AgentTypeEnum.DEFENDANT, caseId);
        }

    }

    /**
     * 保存代理人信息
     * @param agentSaveVOList
     * @param type
     * @param caseId
     */
    private void saveAgent(List<AgentSaveVO> agentSaveVOList, AgentTypeEnum type, Long caseId) {
        agentSaveVOList.stream().forEach(agentSaveVO -> {
            agentSaveVO.setCaseId(caseId);
            agentSaveVO.setType(type.getType());
            Agent agent = this.save(agentSaveVO);
            List<Long> fileIdList = agentSaveVO.getFileIdList();
            if (CollectionUtil.isNotEmpty(fileIdList)) {
                List<AppendixSaveVO> appendixSaveVOList = new ArrayList<>();
                for (int i = 0; i < fileIdList.size(); i++) {
                    Long fileId = fileIdList.get(i);
                    appendixSaveVOList.add(AppendixSaveVO.build(agent.getId(), type.getFileBizType(),
                            fileId, i, null, null));
                }
                appendixService.save(appendixSaveVOList);
            }
        });
    }

    @Override
    public void update(List<AgentUpdateVO> plaintffAgentList, List<AgentUpdateVO> defendantAgentList, Long caseId) {
        if (CollectionUtil.isEmpty(plaintffAgentList)) {
            //未上传原告代理人信息
            this.deleteByCaseIds(Lists.newArrayList(caseId), AgentTypeEnum.PLAINTFF);
        } else {
            updateAgent(plaintffAgentList, AgentTypeEnum.PLAINTFF, caseId);
        }
        if (CollectionUtil.isEmpty(defendantAgentList)) {
            //未上传被告信息
            this.deleteByCaseIds(Lists.newArrayList(caseId), AgentTypeEnum.DEFENDANT);
        } else {
            updateAgent(defendantAgentList, AgentTypeEnum.DEFENDANT, caseId);
        }

    }

    /**
     * 更新代理人信息
     * @param agentList
     * @param caseId
     */
    private void updateAgent(List<AgentUpdateVO> agentList, AgentTypeEnum type, Long caseId) {
        List<Long> updateIdList = agentList.stream().filter(vo ->
                Objects.nonNull(vo.getId())
        ).map(AgentUpdateVO::getId).collect(Collectors.toList());
        List<Agent> oldAgentList = this.findByCaseId(caseId, type.getType());

        //1、需要删除的代理人信息
        List<Long> delAgentIdList = oldAgentList.stream().filter(oldAgent ->
                !updateIdList.contains(oldAgent.getId())
        ).map(Agent::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(delAgentIdList)) {
            appendixService.removeByBizId(delAgentIdList, type.getFileBizType());
            this.removeByIds(delAgentIdList);
        }

        //2、需要新增或更新的代理人信息
        agentList.stream().filter(agentUpdateVO ->
                Objects.isNull(agentUpdateVO.getId()) || !delAgentIdList.contains(agentUpdateVO.getId())
        ).forEach(agentVO -> {
            Agent agent = BeanUtil.toBean(agentVO, Agent.class);
            agent.setCaseId(caseId);
            agent.setType(type.getType());
            superManager.saveOrUpdate(agent);

            List<Long> fileIdList = agentVO.getFileIdList();
            if (CollectionUtil.isNotEmpty(fileIdList)) {
                List<AppendixSaveVO> appendixSaveVOList = new ArrayList<>();
                for (int i = 0; i < fileIdList.size(); i++) {
                    Long fileId = fileIdList.get(i);
                    appendixSaveVOList.add(AppendixSaveVO.build(agent.getId(), type.getFileBizType(),
                            fileId, i, null, null));
                }
                appendixService.save(appendixSaveVOList);
            }
        });
    }

    @Override
    public List<Agent> findByCaseId(Long caseId, Integer type) {
        LbQueryWrap<Agent> queryWrap = Wraps.<Agent>lbQ().eq(Agent::getCaseId, caseId).eq(Agent::getType, type);
        return list(queryWrap);
    }

    @Override
    public List<AgentResultVO> getResultByCaseId(Long caseId, AgentTypeEnum type) {
        List<Agent> agentList = this.findByCaseId(caseId, type.getType());
        List<AgentResultVO> resultVOList = agentList.stream().map(agent -> {
            AgentResultVO agentResultVO = BeanUtil.toBean(agent, AgentResultVO.class);
            List<AppendixResultVO> appendixResultVOS = appendixService.listByBizIdAndBizType(agent.getId(), type.getFileBizType());
            if (CollectionUtil.isEmpty(appendixResultVOS)) {
                //未上传被告图片
                return agentResultVO;
            }
            List<Long> fileIdList = appendixResultVOS.stream().map(AppendixResultVO::getId).collect(Collectors.toList());
            List<File> files = fileService.listByIds(fileIdList);
            //Map<Long, String> accessUrlMap = fileService.findUrlById(fileIdList);
            Map<Long, File> fileMap = files.stream().collect(Collectors.toMap(File::getId, Function.identity()));
            List<CaseFileResultVO> agentFileResultVOList = appendixResultVOS.stream().map(appendixResultVO -> {
                File file = fileMap.get(appendixResultVO.getId());
                CaseFileResultVO caseFileResultVO = new CaseFileResultVO();
                BeanUtils.copyProperties(file, caseFileResultVO);
                BeanUtils.copyProperties(appendixResultVO, caseFileResultVO);
                //caseFileResultVO.setUrl(accessUrlMap.get(file.getId()));
                setPicList(file, caseFileResultVO);
                return caseFileResultVO;
            }).sorted(Comparator.comparing(CaseFileResultVO::getSortValue)).collect(Collectors.toList());
            agentResultVO.setFileList(agentFileResultVOList);
            return agentResultVO;
        }).collect(Collectors.toList());
        return resultVOList;
    }


    private void setPicList(File file, CaseFileResultVO caseFileResultVO) {
        if (BizConstant.SUFFIX_PDF.equalsIgnoreCase(file.getSuffix())) {
            ComFileRel comFileRel = comFileRelManager.getByFileId(file.getId());
            caseFileResultVO.setPicNum(Objects.nonNull(comFileRel) ? comFileRel.getPicNum() : 0);
        } else {
            caseFileResultVO.setPicNum(1);
        }
    }

    @Override
    public Boolean delete(List<Long> ids, String bizType) {
        appendixService.removeByBizId(ids, bizType);
        return removeByIds(ids);
    }

    @Override
    public Boolean deleteByCaseIds(List<Long> caseIds, AgentTypeEnum type) {
        LbQueryWrap<Agent> queryWrap = Wraps.<Agent>lbQ().in(Agent::getCaseId, caseIds).eq(Agent::getType, type.getType());
        List<Agent> agentList = list(queryWrap);
        if (CollectionUtil.isNotEmpty(agentList)) {
            this.delete(agentList.stream().map(Agent::getId).collect(Collectors.toList()), type.getFileBizType());
        }
        return true;
    }

    @Override
    public boolean updateSummarizeInfo(AgentSummarizeUpdateVO agentSummarizeUpdateVO) {
        Agent agent = new Agent();
        agent.setId(agentSummarizeUpdateVO.getId());
        agent.setSummarizeInfo(agentSummarizeUpdateVO.getSummarizeInfo());
        return this.superManager.updateById(agent);
    }

}


